package com.yuushya.utils.controller

import com.yuushya.datagen.ZipReader
import com.yuushya.datagen.ZipWriter
import com.yuushya.utils.MapConvert
import jakarta.servlet.http.HttpServletResponse
import org.apache.tomcat.util.http.fileupload.IOUtils
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestPart
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.net.URLEncoder
import java.nio.file.Files
import java.util.zip.ZipOutputStream
import kotlin.io.path.exists

@RestController
@RequestMapping("/api")
class MapConvertor{
    init{
        MapConvert.readMap()
    }
    @PostMapping("/map-convertor/upload")
    fun upload(
        @RequestPart file: MultipartFile,
        response: HttpServletResponse
    ){

        //获取文件全名
        val fileName = file.originalFilename?:"temp"
        //文件上传路径对象
        val uploadFolder = Files.createTempDirectory("temp")
        //压缩包存储目标文件对象
        val destPath = uploadFolder.resolve("./$fileName");

        //步骤1、把上传的压缩包文件保存到指定压缩包路径
        file.transferTo(destPath)

        //解压目标文件夹对象（压缩文件解压到此文件夹中）
        val extractFolder =  uploadFolder.resolve("./extract").also {
            //判断解压后文件夹是否存在//不存在就创建
            if(!it.exists())  Files.createDirectory(it)
        };

        val zipReader= ZipReader(destPath, extractFolder)
        zipReader.unzip()

        MapConvert.readSave(extractFolder) { MapConvert.readFileByQNBT(it) }

        val fileNameNew = "new-${fileName}"
        val downloadFileName = URLEncoder.encode(fileNameNew, "UTF-8")
        val outputPath =uploadFolder.resolve("./$fileNameNew")

        val zipWriter = ZipWriter(extractFolder,outputPath)

        // 设置文件下载方式：附件下载
        response.setHeader("Content-Disposition", "attachment;fileName=$downloadFileName");
        response.addHeader("resource-filename", downloadFileName)
        response.setHeader("Access-Control-Expose-Headers","resource-filename");
        response.contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;

        ZipOutputStream(response.outputStream).use {
            it.setMethod(ZipOutputStream.DEFLATED)
            zipWriter.zip(it)
        }
        Dustbin.throwJunk(uploadFolder)
        //FileUtils.deleteAll(extractFolder)

    }
}
